#!/usr/bin/python
'''
/*
 * This computer program is the confidential information and proprietary trade
 * secret of VistaraIT LLC.  Possessions and use of this program must  conform
 * strictly to the license agreement between the user and VistaraIT LLC.,  and
 * receipt or possession does not convey any rights to divulge, reproduce,  or
 * allow others to use this program without specific written authorization  of
 * VistaraIT LLC.
 * 
 * Copyright (c) 2014 VistaraIT, Inc. All rights reserved.
 */
'''

#from licensemanager import LicenseManager
from networkutils import NetworkUtils
from datetimeinfo import DateTimeInfo
from django.template.loader import render_to_string
from configmanager import ConfigManager
from xmlreader import XMLReader
import os, time, base64, socket
import pycurl, StringIO
from registerappliance import RegisterAppliance
from tunnelmanager import TunnelManager
from debugappliance import DebugAppliance
import platform
from datetime import timedelta
from commons import executeCommand, processTemplateTOFile,parseUpdateResponse
import applicationproperties as properties
import logger

class ApplianceManager():

    service_map={'monitoring':'nagios','neprobe':'neprobe','discovery':'neprobe'}
    errorcode_map={'200':'Successfully Connected', '302':'Connection Redirected', '400':'Bad Request.', '401':'WWW Authentication Required.', '403':'Forbidden Error.', '405':'Method Not Allowed.', '407':'Proxy Authentication Required.', '501':'Not Implemented.', '503':'Service Not Available.'}

    def __init__(self):
        self.cfgmanager = ConfigManager()
        self.regInfo = RegisterAppliance(self)
        self.debugInfo = DebugAppliance(self)
        self.tunnelInfo = TunnelManager(self)
        self.networkutils = NetworkUtils()        
        self.verInfo = {}
        self.basicHwInfo = {}
        
    def getApplianceInfo(self):
        appliance = {}
        appliance['regInfo'] = self.getRegistrationInfo()
        appliance['networkInfo'] = self.getNetworkInfo()
        appliance['tunnelInfo'] = self.getTunnelInfo()
        try:
            appliance['versionInfo'] = self.getVersionInfo()
        except:
            pass
        
        appliance['basicHardwareInfo'] = self.getBasicHardwareInfo()
                
        return appliance
    
    def getBasicHardwareInfo(self):
        if not self.basicHwInfo:
            cmd = "/usr/bin/sudo /usr/bin/free -m 2>/dev/null | grep 'Mem:' | awk '{print $2}'"
            self.basicHwInfo['totalMemory'] = executeCommand(cmd,[],True)[1]
            
            cmd = "/usr/bin/sudo /sbin/fdisk -l 2>/dev/null | grep Disk | awk '{print $5}'"
            result = executeCommand(cmd,[],True)[1]
            hddArr = result.split("\n")
            totalHDD = ""
            for disk in hddArr:
                totalHDD = totalHDD + str(disk) + ","
            self.basicHwInfo['physicalHDD'] = totalHDD.rstrip(",")
            
            cmd = "/usr/bin/sudo /bin/grep -c processor /proc/cpuinfo"
            self.basicHwInfo['cpuCount'] = executeCommand(cmd,[],True)[1]
    
            cmd = "/usr/bin/sudo /bin/uname -r 2>/dev/null"
            self.basicHwInfo['kernelVer'] = executeCommand(cmd,[],True)[1]
            
            cmd = "/usr/bin/sudo /bin/uname -m 2>/dev/null"
            result = executeCommand(cmd,[],True)
            if result[1] == "i686":
                self.basicHwInfo['arch'] = "x86"
            elif result[1] == "x86_64":
                self.basicHwInfo['arch'] = "x64"
            else:
                self.basicHwInfo['arch'] = ""
    
            try:
                cmd = "/usr/bin/sudo /usr/bin/lsb_release -ds 2>/dev/null"
                self.basicHwInfo['os'] = executeCommand(cmd, [], True)[1].strip()
            except:
                pass
            
        return self.basicHwInfo
    
    def getVersionInfo(self):
        if not self.verInfo:
            hardwareInfo = self.readFileProperties(properties.NSG_HW_INFO_FILE)
            self.verInfo['model'] = hardwareInfo['APPLIANCE_MODEL']
            self.verInfo['build'] = hardwareInfo['APPLIANCE_BUILDTAG']
            self.verInfo['platform'] = hardwareInfo['APPLIANCE_PLATFORM']
            self.verInfo['buildnumber'] = hardwareInfo['APPLIANCE_BUILDNUMBER']
            self.verInfo.update(self.getModuleVersion())
            
        return self.verInfo
        
    def getApplianceHardwareInfo(self):
        nsgHardwareInfo = {}
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'bios-vendor 2>/dev/null | head -1'
            nsgHardwareInfo['bios_vendor'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['bios_vendor'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'bios-version 2>/dev/null | head -1'
            nsgHardwareInfo['bios_version'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['bios_version'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE + " -t bios 2>/dev/null | /bin/grep 'ROM Size' | /usr/bin/cut -d':' -f2"
            nsgHardwareInfo['bios_rom_size'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['bios_rom_size'] = ""

        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'system-manufacturer 2>/dev/null | head -1'
            nsgHardwareInfo['system_manufacturer'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['system_manufacturer'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'system-product-name 2>/dev/null | head -1'
            nsgHardwareInfo['system_product_name'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['system_product_name'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'baseboard-manufacturer 2>/dev/null | head -1'
            nsgHardwareInfo['motherboard_manufacturer'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['motherboard_manufacturer'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'baseboard-product-name 2>/dev/null | head -1'
            nsgHardwareInfo['motherboard_product_name'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['motherboard_product_name'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'chassis-manufacturer 2>/dev/null | head -1'
            nsgHardwareInfo['chassis_manufacturer'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['chassis_manufacturer'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'processor-manufacturer 2>/dev/null | head -1'
            nsgHardwareInfo['processor_manufacturer'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['processor_manufacturer'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'processor-family 2>/dev/null | head -1'
            nsgHardwareInfo['processor_family'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['processor_family'] = ""
            
        try:
            cmd = properties.CMD_DMIDECODE_STRING + 'processor-frequency 2>/dev/null | head -1'
            nsgHardwareInfo['processor_frequency'] = executeCommand(cmd, [], True)[1].strip()
        except:
            nsgHardwareInfo['processor_frequency'] = ""

        try:
            cmd = properties.CMD_LSHW + " -c disk 2>/dev/null"
            diskArr = executeCommand(cmd, [], True)[1].strip().split("*")
            for disk in diskArr:
                if disk.startswith("-disk"):
                    try:
                        cmd = "echo \"" + disk + "\" | /bin/grep 'size' | head -1 | /usr/bin/cut -d':' -f2"
                        nsgHardwareInfo['hdd_size'] = executeCommand(cmd, [], True)[1].strip()
                    except:
                        nsgHardwareInfo['hdd_size'] = ""
                    
                    try:
                        cmd = "echo \"" + disk + "\" | /bin/grep 'product' | head -1 | /usr/bin/cut -d':' -f2"
                        nsgHardwareInfo['hdd_product'] = executeCommand(cmd, [], True)[1].strip()
                    except:
                        nsgHardwareInfo['hdd_product'] = ""
                    
                    try:
                        cmd = "echo \"" + disk + "\" | /bin/grep 'vendor' | head -1 | /usr/bin/cut -d':' -f2"
                        nsgHardwareInfo['hdd_vendor'] = executeCommand(cmd, [], True)[1].strip()
                    except:
                        nsgHardwareInfo['hdd_vendor'] = ""
                    break;
        except:
            nsgHardwareInfo['hdd_size'] = ""
            nsgHardwareInfo['hdd_product'] = ""
            nsgHardwareInfo['hdd_vendor'] = ""
        
        try:
            cmd = properties.CMD_LSHW + " -xml"
            lshwXML = executeCommand(cmd, [], True)[1].strip()
            nsgHardwareInfo['hw_info'] = base64.b64encode(lshwXML).strip()
        except:
            nsgHardwareInfo['hw_info'] = ""
        return nsgHardwareInfo
    
    def isRegistered(self):
        return self.regInfo.isRegistered()

    def establishTunnel(self):
        return self.tunnelInfo.establishTunnel()
    
    def updateApplianceHardwareInfo(self):
        try:
            nsgHardwareInfo = {}
            try:
                cmd = "/usr/bin/sudo /usr/bin/imvirt 2>/dev/null | /usr/bin/head -n 1 | cut -d':' -f1"
                platform = executeCommand(cmd,[],True)[1]
            except:
                platform = ""
            nsgHardwareInfo['APPLIANCE_PLATFORM'] = platform

            cmd = "/usr/bin/sudo /bin/echo " + platform + " | grep -i xen"
            isXEN = executeCommand(cmd, [], True)[0] == 0
            
            cmd = "/usr/bin/sudo /bin/uname -r 2>/dev/null | /bin/grep -i '-ec2'"
            isCloud = executeCommand(cmd, [], True)[0] == 0

            if isXEN and isCloud:
                model = "SGAMI"
            elif platform.lower() != "physical":
                model = "SGVMA"
            else:
                try:
                    cmd = "/usr/bin/sudo /usr/sbin/dmidecode -s baseboard-product-name 2>/dev/null"
                    productName = executeCommand(cmd,[],True)[1]
                except:
                    productName = ""
                if productName == "EB1007":
                    model = "SG100"
                elif productName == "DQ45EK":
                    model = "SG300"
                elif productName == "DH61DL":
                    model = "SG301"
                elif productName == "X7SBi" or productName == "X8SIL":
                    model = "SG400"
                else:
                    model = properties.UNKNOWN_MODEL_TAG
            nsgHardwareInfo['APPLIANCE_MODEL'] = model
            
            cmd = "/usr/bin/sudo cat /home/admin/logs/kickstart-info | /bin/grep BuildVersion | cut -d ' ' -f2"
            nsgHardwareInfo['APPLIANCE_BUILDTAG'] = executeCommand(cmd,[],True)[1]
            
            cmd = "/usr/bin/sudo cat /home/admin/logs/kickstart-info | /bin/grep BuildNumber | cut -d ' ' -f2"
            nsgHardwareInfo['APPLIANCE_BUILDNUMBER'] = executeCommand(cmd,[],True)[1]

            self.updateFileProperties(properties.NSG_HW_INFO_FILE, nsgHardwareInfo)
            cmd1 = "/usr/bin/sudo chown admin.admin " + properties.NSG_HW_INFO_FILE + " >/dev/null 2>&1"    
            cmd2 = "/usr/bin/sudo chmod 755 " + properties.NSG_HW_INFO_FILE + " >/dev/null 2>&1"
            executeCommand(cmd1,[],True)
            executeCommand(cmd2,[],True)
            return True
        except:
            return False

    def initializeNetwork(self, networkInfo, kvm=0):
        try:
            if (not networkInfo.has_key('default_iface')) or networkInfo['default_iface'] == None or networkInfo['default_iface'] == "" or networkInfo['default_iface'] == "UNKNOWN":
                networkInfo['default_iface'] = "eth0"
                
            if self.changeHostName(networkInfo['hostname'], networkInfo['domainname']):
                logger.logMessage(logger.INFO, 'initialize network', "Successfully updated hostname.")
            
            is_precise = True if platform.dist()[2] == 'precise' else False
            processTemplateTOFile('config/interfaces', properties.WORK_IFCFG_ETH0, { 'networkInfo': networkInfo, 'is_precise': is_precise })
            executeCommand(properties.CMD_CP_IFCFG_ETH0)
            logger.logMessage(logger.INFO, 'initialize network', properties.CMD_CP_IFCFG_ETH0)
    
            executeCommand(properties.CMD_NETWORK_RESTART)
            time.sleep(2)

            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_IFCFG_ETH0
            executeCommand(cmd, [], True)
            executeCommand(properties.CMD_GEN_BANNER, [], True)
            return True
        except:
            logger.logMessage(logger.ERROR, 'initialize network', "Failed to initialize network. Exception Caught")
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_IFCFG_ETH0
            executeCommand(cmd, [], True)
            return False
        
    
    def changeHostName(self, hostname, domainname):
        try:
            executeCommand(properties.CMD_HOST_NAME,[hostname + "." + domainname])
            processTemplateTOFile('config/hosts',properties.WORK_HOSTS,{ 'hostname':hostname,'domainname':domainname })
            processTemplateTOFile('config/hostname',properties.WORK_HOSTNAME,{ 'hostname':hostname,'domainname':domainname })
            executeCommand(properties.CMD_CP_HOSTS)
            executeCommand(properties.CMD_CP_HOSTNAME)
            cmd = properties.CMD_SUDO + " /usr/sbin/service hostname restart"
            result = executeCommand(cmd, [], True)
            output = result[1].replace("'","")
            logger.logMessage(logger.INFO, 'HostName', output)
            
            cmd = "/usr/bin/sudo /usr/bin/service snmpd restart"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                logger.logMessage(logger.ERROR, 'HostName', "Failed to restart SNMP service.")
            else:
                logger.logMessage(logger.INFO, 'HostName', "Successfully restarted SNMP service.")
            
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_HOSTS
            executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_HOSTNAME
            executeCommand(cmd, [], True)
            return True
        except:
            logger.logMessage(logger.ERROR, 'Network', 'Failed to update Host Name. Exception Caught')
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_HOSTS
            executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_HOSTNAME
            executeCommand(cmd, [], True)
            return False

    def updateNetworkConfig(self, networkInfo):
        try:
            #logger.logMessage(logger.INFO, 'network', str(networkInfo))
            srouteStrArr = self.getStaticRouteStrings()
            network = self.networkutils
            vlanArr = network.getVlans()
            phyInterfacesInfo = network.getPhyInterfacesInfo()
            
            if networkInfo['default_iface'] == None or networkInfo['default_iface'] == "" or networkInfo['default_iface'] == "UNKNOWN":
                networkInfo['default_iface'] = "eth0"
            
            if self.changeHostName(networkInfo['hostname'], networkInfo['domainname']):
                logger.logMessage(logger.INFO, 'network', "Successfully updated hostname.")
    
            logger.logMessage(logger.INFO, 'network', "Updating Network Configuration")
           
            is_precise = True if platform.dist()[2] == 'precise' else False
            if networkInfo['vlanid'] != "":
                processTemplateTOFile('config/interfaces-vlan-ethx',properties.WORK_IFCFG_ETH0,{ 'networkInfo': networkInfo,'srouteStrArr':srouteStrArr,'vlanArr':vlanArr, 'phyInterfacesInfo': phyInterfacesInfo, 'is_precise': is_precise })
            else:
                processTemplateTOFile('config/interfaces',properties.WORK_IFCFG_ETH0,{ 'networkInfo': networkInfo,'srouteStrArr':srouteStrArr,'vlanArr':vlanArr, 'phyInterfacesInfo': phyInterfacesInfo, 'is_precise': is_precise })
            executeCommand(properties.CMD_CP_IFCFG_ETH0)
            logger.logMessage(logger.INFO, 'Network', properties.CMD_CP_IFCFG_ETH0)
    
            #update domain name and resolv conf only if it is static ip
            if networkInfo['dhcp'] == False:
                is_precise = True if platform.dist()[2] == 'precise' else False
                if  is_precise == False:
                    processTemplateTOFile('config/resolv.conf',properties.WORK_RESOLV_CONF,{ 'networkInfo': networkInfo })
                    executeCommand(properties.CMD_CP_RESOLV_CONF)
                    logger.logMessage(logger.INFO, 'Network', properties.CMD_CP_RESOLV_CONF)
                    cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_RESOLV_CONF
                    executeCommand(cmd, [], True)

                cmd = "/usr/bin/sudo /bin/kill -9 `pgrep -f 'dhclient3'`";
                executeCommand(cmd, [], True)
    
            result = executeCommand(properties.CMD_NETWORK_RESTART)
            output = result[1].replace("'","")
            logger.logMessage(logger.INFO, 'Network Restart', output)
            time.sleep(2)
            executeCommand(properties.CMD_NETWORK_RESTART)
            time.sleep(2)
            executeCommand(properties.CMD_GEN_BANNER, [], True)
            
            #finally delete temp files
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_IFCFG_ETH0
            executeCommand(cmd, [], True)
        except Exception as emg:
            logger.logMessage(logger.ERROR, 'Network', 'Caught exception during network update' + str(emg))
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_IFCFG_ETH0
            executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_RESOLV_CONF
            executeCommand(cmd, [], True)


    def updateVlanConfig(self):
        try:
            networkInfo = self.getNetworkInfo()
            vlanArr = networkInfo['vlans']
            srouteStrArr = self.getStaticRouteStrings()
            phyInterfacesInfo = networkInfo['phyInterfacesInfo']
            
            if networkInfo['default_iface'] == None or networkInfo['default_iface'] == "" or networkInfo['default_iface'] == "UNKNOWN":
                networkInfo['default_iface'] = "eth0"
            
            is_precise = True if platform.dist()[2] == 'precise' else False
            if networkInfo['vlanid'] != "":
                processTemplateTOFile('config/interfaces-vlan-ethx',properties.WORK_IFCFG_ETH0,{ 'networkInfo': networkInfo,'srouteStrArr':srouteStrArr,'vlanArr':vlanArr,'phyInterfacesInfo': phyInterfacesInfo, 'is_precise': is_precise })
            else:
                processTemplateTOFile('config/interfaces',properties.WORK_IFCFG_ETH0,{ 'networkInfo': networkInfo,'srouteStrArr':srouteStrArr,'vlanArr':vlanArr, 'phyInterfacesInfo': phyInterfacesInfo, 'is_precise': is_precise })
            executeCommand(properties.CMD_CP_IFCFG_ETH0)
            result = executeCommand(properties.CMD_NETWORK_RESTART)
            logger.logMessage(logger.INFO, 'VLan', result[1])
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_IFCFG_ETH0
            executeCommand(cmd, [],True)
        except:
            logger.logMessage(logger.INFO, 'VLan', "Caught exception during vlans update")
    
    def updateStaticRouteConfig(self):
        try:
            networkInfo = self.getNetworkInfo()
            srouteStrArr = self.getStaticRouteStrings()
            vlanArr = networkInfo['vlans']
            phyInterfacesInfo = networkInfo['phyInterfacesInfo']
            
            if networkInfo['default_iface'] == None or networkInfo['default_iface'] == "" or networkInfo['default_iface'] == "UNKNOWN":
                networkInfo['default_iface = "eth0"']
                
            is_precise = True if platform.dist()[2] == 'precise' else False
            if networkInfo['vlanid'] != "":
                processTemplateTOFile('config/interfaces-vlan-ethx',properties.WORK_IFCFG_ETH0,{ 'networkInfo': networkInfo,'srouteStrArr':srouteStrArr,'vlanArr':vlanArr,'phyInterfacesInfo': phyInterfacesInfo, 'is_precise': is_precise })
            else:
                processTemplateTOFile('config/interfaces',properties.WORK_IFCFG_ETH0,{ 'networkInfo': networkInfo,'srouteStrArr':srouteStrArr,'vlanArr':vlanArr,'phyInterfacesInfo': phyInterfacesInfo, 'is_precise': is_precise })
            executeCommand(properties.CMD_CP_IFCFG_ETH0)
            result = executeCommand(properties.CMD_NETWORK_RESTART)
            logger.logMessage(logger.INFO, 'Update Static Routes', result[1])
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_IFCFG_ETH0
            executeCommand(cmd, [],True)
        except:
            logger.logMessage(logger.INFO, 'Update Static Routes', "Caught exception during static routes update")

    def getStaticRouteStrings(self):
        try:
            srouteStrArr = []
            networkInfo = self.getNetworkInfo()
            sroutesArr = networkInfo['sroutes']
            for route in sroutesArr:
                _str = "up route add -net " + route[0] + " gw " + route[1] + " netmask " + route[2] + " metric " + route[3] + " dev " + route[4] + "\n"
                srouteStrArr.append(_str)
            return srouteStrArr
        except:
            return []
    
    def dnsCheck(self,host):
        try:
            if host == None or host.strip() == "":
                return False, "NA"
            dnsName = socket.gethostbyname(host)
            return True, dnsName
        except Exception as (errno, errmsg):
            logger.logMessage(logger.ERROR, 'DNS Check', "Exception caught: " + str(errno) + " - " + str(errmsg))
            return False, errmsg
        
    def updateVirtualIP(self):
        executeCommand(properties.CMD_CP_VIRT_ETH0,[],True)
        logger.logMessage(logger.INFO, 'Network', properties.CMD_CP_VIRT_ETH0)
        cmd = "/usr/bin/sudo chmod 644 " + properties.SYSCONFIG_VIRT_ETH0 + " >/dev/null 2>&1"
        executeCommand(cmd,[],True)
    
    def getRegistrationStatusFlag(self,status = False):
        if status:
            return 'Registered'
        return 'Not Registered'
    
    '''
    def installLicense(self):
        # check if appliance is registered
        if self.checkRegistration() == False:
            logger.logMessage(logger.INFO, 'Install License', 'Appliance not yet registered.')
            return False

        licenseManager = LicenseManager(self)
        installStatus, errorMsg = licenseManager.installLicense()
        logger.logMessage(logger.ERROR, 'LicenseStatus', str(installStatus) + " - " + str(errorMsg))

        params = {}
        try:
            if installStatus:
                params['status'] = "success"
            else:
                params['status'] = "failed"
            params['errorMsg'] = errorMsg
            url = self.toUpdateServerURL(properties.LICENSE_INSTALL_STATUS)
            
            statusMsg = licenseManager.prepareLicenseData("LicenseStatus", "cpe", params)
            logger.logMessage(logger.INFO, 'LicenseStatus Intimate', statusMsg)
            
            status, response = self.postXMLData(url,statusMsg)
            logger.logMessage(logger.INFO, 'LicenseStatus Response', str(status) + " " + str(response))
            
            parseVal = parseUpdateResponse(response, "status")
            if status == 200 and parseVal == "success":
                logger.logMessage(logger.INFO, 'LicenseStatus', 'Intimated license install status to SCC.')
            else:
                logger.logMessage(logger.ERROR, 'LicenseStatus', 'Failed to intimate license install status to SCC.')
        except Exception as (errno,errmsg):
            if errno == 111:
                logger.logMessage(logger.ERROR, 'Connection Exception', str(errno) + " - " + str(errmsg))
            elif errno == 101:
                logger.logMessage(logger.ERROR, 'Network Exception', str(errno) + " - " + str(errmsg))
            else:
                logger.logMessage(logger.ERROR, 'Caught Exception', str(errno) + " - " + str(errmsg))
        return installStatus
    
    '''
    '''
    Method to check of ssh process is running or not
    '''
    def isTunnelRunning(self):
        return self.tunnelInfo.isTunnelRunning()
    
    def isNTPON(self):
        try:
            return executeCommand(properties.CMD_NTP_STATUS)[0] == 0
        except:
            return False

    def ntpSYNC(self,server1,server2):
        try:
            cmd = "/usr/bin/sudo /usr/bin/monit status | grep \"Process '" + properties.JSVC_SERVICE_NAME + "'\""
            nemsMonitStatus = executeCommand(cmd,[],True)[0]
            if nemsMonitStatus == 0:
                cmd = "/usr/bin/sudo /home/admin/bin/servicemonit " + properties.JSVC_SERVICE_NAME + " stop"
                result = executeCommand(cmd,[],True)
                if result[0] != 1:
                    logger.logMessage(logger.ERROR,'NtpSync',"Failed to stop " + properties.JSVC_SERVICE_NAME + " service.")
                else:
                    logger.logMessage(logger.INFO,'NtpSync',"Stopped the " + properties.JSVC_SERVICE_NAME + " service.")
            else:
                logger.logMessage(logger.INFO,'NtpSync',properties.JSVC_SERVICE_NAME + " service is not yet initialized in Monit.")
                
            cmd = "/usr/bin/sudo /usr/bin/service ntp stop"
            result = executeCommand(cmd,[],True)
            if result[0] != 0:
                logger.logMessage(logger.ERROR,'NtpSync',"Failed to stop Ntp service.")
            else:
                logger.logMessage(logger.INFO,'NtpSync',"Stopped the Ntp service.")
            
            syncStatus = 0
            result = executeCommand(properties.CMD_NTP_SYNC,[server1],True)
            result = executeCommand(properties.CMD_NTP_SYNC,[server1],True)
            result = executeCommand(properties.CMD_NTP_SYNC,[server1],True)
            if result[0] != 0:
                logger.logMessage(logger.ERROR,'NtpSync',"Failed to sync to " + server1)
                result1 = executeCommand(properties.CMD_NTP_SYNC,[server2],True)
                result1 = executeCommand(properties.CMD_NTP_SYNC,[server2],True)
                result1 = executeCommand(properties.CMD_NTP_SYNC,[server2],True)
                if result1[0] != 0:
                    logger.logMessage(logger.ERROR,'NtpSync',"Failed to sync to " + server2)
                    syncStatus = 1
                else:
                    logger.logMessage(logger.INFO,'NtpSync',"Ntp sync successful to " + server2)
            else:
                logger.logMessage(logger.INFO,'NtpSync',"Ntp sync successful to " + server1)
            
            if nemsMonitStatus == 0:
                cmd = "/usr/bin/sudo /home/admin/bin/servicemonit " + properties.JSVC_SERVICE_NAME + " start"
                result = executeCommand(cmd,[],True)
                if result[0] != 0:
                    logger.logMessage(logger.ERROR,'NtpSync',"Failed to start " + properties.JSVC_SERVICE_NAME + " service.")
                    return False
                else:
                    logger.logMessage(logger.INFO,'NtpSync',"Started the " + properties.JSVC_SERVICE_NAME + " service.")
            cmd = "/usr/bin/sudo /usr/bin/service ntp start"
            result = executeCommand(cmd,[],True)
            if result[0] != 0:
                logger.logMessage(logger.ERROR,'NtpSync',"Failed to start Ntp service.")
                return False
            else:
                logger.logMessage(logger.INFO,'NtpSync',"Started the Ntp service.")
            
            if syncStatus != 0:
                return False
            return True
        except:
            return False
    
    def ntpON(self,server1,server2):
        try:
            if os.path.exists(properties.WORK_NTP_CONF):
                cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_NTP_CONF
                executeCommand(cmd, [],True)
            executeCommand(properties.CMD_NTP_STOP,[],True)
            processTemplateTOFile('config/ntp.conf',properties.WORK_NTP_CONF,{ 'ntpserverprimary': server1, 'ntpserversecondary': server2 })
            executeCommand(properties.CMD_CP_NTP_CONF)
            executeCommand(properties.CMD_NTP_START)
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.WORK_NTP_CONF
            executeCommand(cmd, [],True)
        except:
            logger.logMessage(logger.ERROR,'NtpOn',"Failed to update the Ntp configuration file.")
            pass
        
    def ntpOFF(self):
        executeCommand(properties.CMD_NTP_STOP,[],True)
    
    def ntpSYNCStatus(self,server1,server2):
        return executeCommand(properties.CMD_NTP_SYNC_STATUS, [server1,server2], True)[0] == 0
        
    def getNTPServers(self):
        ntp = []
        try:
            result = executeCommand("cat /etc/ntp.conf | grep '^server' | awk '{print $2}' | head -n 1")
            if result[0] == 0:
                ntp.append(result[1])
            result = executeCommand("cat /etc/ntp.conf | grep '^server' | awk '{print $2}' | head -n 2 | tail -n 1")
            if result[0] == 0:
                ntp.append(result[1])
        except:
            ntp.append('')
            ntp.append('')
        return ntp
    
    def getNetworkInfo(self):
        return self.networkutils.getNetworkInfo()
    '''
    def getUptime(self):
	with open('/proc/uptime','r') as f:
		uptime_sec = (float(f.readline().split()[0])
		uptime_str = str(timedelta(seconds = uptime_sec))
	return uptime_str
       ''' 
    def getDateTimeInfo(self):
        dateInfo = DateTimeInfo()
        dateInfo.timezone = self.getTimeZone()
        dateInfo.currentTimeStr = executeCommand("date", [], True)[1]
        dateInfo.ntpON = self.isNTPON()
        ntpservers = self.getNTPServers()
        dateInfo.ntpserver1 = ntpservers[0]
        dateInfo.ntpserver2 = ntpservers[1]
        if dateInfo.ntpON:
            dateInfo.ntpSYNCStatus = self.ntpSYNCStatus(dateInfo.ntpserver1,dateInfo.ntpserver2)
        return dateInfo
    
    def authenticateAdmin(self,username,password):
        try:
            if username is None or password is None or username != 'admin':
                raise Exception("Invalid username or password")
            return executeCommand(properties.APPLIANCE_PWD_VAL_COMMAND,[password])[0] == 0
        except:
            return False

    def changePassword(self,username,currentpass,newpass,repeatpass):
        try:
            return executeCommand(properties.APPLIANCE_CHG_PWD_COMMAND,[username,currentpass,newpass,repeatpass])[0] == 0
        except:
            return False
    
    def getTimeZone(self):
        try:
            tzstring = executeCommand("/bin/cat /etc/timezone", [], True)[1].strip()
            array = tzstring.split("/")
            cnt = len(array)
            timezone = array[cnt-1]
            return timezone
        except:
            return 'Pacific'
    
    def setTimeZone(self,zone):
        if self.getTimeZone() == zone:
            return True
        return executeCommand(properties.APPLIANCE_SET_TIMEZONE,["TZ='"+zone+"'"])[0] == 0
        
    def setDateTime(self,date,time):
        #setting date manually should force ntp off
        self.ntpOFF()
        date1 = date.replace('-', '/').replace('.', '/')
        return executeCommand(properties.CMD_SET_DATE,["'" + time + ' ' + date1 + "'"])[0] == 0
        
    def getProxySettings(self):
        form = {}
        form['connection'] = self.cfgmanager.getProxyProperties(self.cfgmanager.NETWORK_CON_TYPE)
        form['proxy_ip'] = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_IP)
        form['proxy_port'] = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PORT)
        form['proxy_usr'] = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_USR)
        form['proxy_pwd'] = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PWD)
        return form
    
    def setProxySetting(self,settings):
        try:
            if settings['connection'] == 'direct':
                self.cfgmanager.setProxySetting(settings['connection'])
            else:
                self.cfgmanager.setProxySetting(settings['connection'], settings['proxy_ip'], settings['proxy_port'], settings['proxy_usr'], settings['proxy_pwd'])
            return True
        except:
            return False
    
    
    '''
    def checkLicense(self):
        licenseManager = LicenseManager(self)
        return licenseManager.checkLicense()
    '''
    
    '''
    # Function to place property file
    def CopyLBProperties(self):
        macId = self.getServiceTag()
        processTemplateTOFile('config/LBProperties.properties',properties.LBPROPERTY_WORK_FILE,{ 'nda_auth_token': macId })
        cmd = "/usr/bin/sudo /bin/mv -f " + properties.LBPROPERTY_WORK_FILE + " " + properties.LB_PROPERTY_FILE + " >/dev/null 2>&1"
        executeCommand(cmd)
        cmd1 = "/usr/bin/sudo chown nems.nems " + properties.LB_PROPERTY_FILE + " >/dev/null 2>&1"    
        cmd2 = "/usr/bin/sudo chmod 755 " + properties.LB_PROPERTY_FILE + " >/dev/null 2>&1"
        executeCommand(cmd1,[],True)
        executeCommand(cmd2,[],True)
    '''    
    
    def checkRemoteConnection(self):
        try:
            url = self.toUpdateServerURL(properties.URL_SUPPORT_PING)
            
            conn_type = self.cfgmanager.getProxyProperties(self.cfgmanager.NETWORK_CON_TYPE)
            c = pycurl.Curl()
            strio = StringIO.StringIO()

            c.setopt(pycurl.URL, str(url))
            c.setopt(pycurl.HTTPGET, 1)
            c.setopt(pycurl.VERBOSE, 0)
            if conn_type != "direct":
                proxy_ip = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_IP)
                proxy_port = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PORT)
                proxy_usr = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_USR)
                proxy_pwd = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PWD)
                c.setopt(pycurl.PROXY, proxy_ip)
                c.setopt(pycurl.PROXYPORT, int(proxy_port))
                c.setopt(pycurl.PROXYAUTH, pycurl.HTTPAUTH_BASIC)
                if proxy_usr != "" and proxy_pwd != "":
                    c.setopt(pycurl.PROXYUSERPWD, proxy_usr + ":" + proxy_pwd)
                else:
                    pass
            else:
                pass

            c.setopt(pycurl.SSL_VERIFYPEER, False)
            c.setopt(pycurl.SSL_VERIFYHOST, False)
            c.setopt(pycurl.TIMEOUT, 120)
            c.setopt(pycurl.CONNECTTIMEOUT, 60)
            
            c.setopt(pycurl.WRITEFUNCTION, strio.write)
            c.setopt(pycurl.FOLLOWLOCATION, 1)
            c.setopt(pycurl.MAXREDIRS, 5)
            c.perform()
            content = strio.getvalue()
            response = c.getinfo(pycurl.HTTP_CODE)
            
            if response != 200:
                logger.logMessage(logger.ERROR, 'SupportConnection', "Support site is not reachable. " + str(content))
                return False
            
            parseVal = parseUpdateResponse(content, "response_token")

            if parseVal == properties.URL_SUPPORT_TOKEN:
                logger.logMessage(logger.INFO, 'SupportConnection', "Got response token from support site: " + parseVal)
                return True
            else:
                logger.logMessage(logger.ERROR, 'SupportConnection', "Support site is not reachable")
                return False
        except Exception as errmsg:
            logger.logMessage(logger.ERROR, 'SupportConnection', "Exception caught: " + str(errmsg))
            return False
    
    def prepareLogFiles(self):
        logFiles = properties.ADMIN_LOGS_DIR + " " + properties.VAR_LOG_FILES + " " + properties.NEMS_LOGS_DIR + " " + properties.NGINX_LOG_DIR + " " + properties.VAR_SYSLOG_FILE
        if os.path.exists(properties.UPGRADES_LOGFILE):
            cmd = "/usr/bin/sudo chown admin.admin " + properties.UPGRADES_LOGFILE + " >/dev/null 2>&1"
            executeCommand(cmd,[],True)
            logFiles = logFiles + " " + properties.UPGRADES_LOGFILE
        tarCmd = "/usr/bin/sudo /bin/tar --ignore-failed-read -cjf " + properties.WORK_DIR + "logs.bz2 " + logFiles
        result = executeCommand(tarCmd,[],True)
        cmd = "/usr/bin/sudo chown admin.admin " + properties.WORK_DIR + "logs.bz2 >/dev/null 2>&1"
        executeCommand(cmd,[],True)
        if result[0] != 0:
            logger.logMessage(logger.INFO, 'DownloadLogs', "Log Files tar failed.")
            logger.logMessage(logger.INFO, 'DownloadLogs', "Tar Command: " + tarCmd)
            return False
        
        encCmd = properties.CMD_ENCRYPT_LOGS + properties.WORK_DIR + "logs.bz2 " + properties.DATA_DIR + "logs"
        result = executeCommand(encCmd,[],True)
        if result[0] != 0:
            logger.logMessage(logger.INFO, 'DownloadLogs', "Encryption of logs tar file failed.")
            logger.logMessage(logger.INFO, 'DownloadLogs', "Encryption Command: " + encCmd)
            return False
        cmd = "/usr/bin/sudo chmod 755 " + properties.DATA_DIR + "logs >/dev/null 2>&1"
        executeCommand(cmd,[],True)
        return True
    
    def reconnectTunnel(self):
        if self.kill_tunnels():
            return self.establishTunnel()
        else:
            False, "Failed to disconnect tunnel"
        
    
    
    def applicationStatus(self):
        try:
            apps1Status = {('nagios','Monitoring'):False,('neprobe','NEProbe'):False,('ntp','NTP'):False,('nodeMgr','HeartBeat'):False,('postgresql','Database'):False,('network','Network'):False}
            apps2Status = {('vsftpd','FTP'):False,('tftpd-hpa','TFTP'):False,(properties.DHCP_INIT_SERVICE,'DHCP'):False}
            for key in apps1Status.iterkeys():
                if key[0] == "network":
                    cmd = properties.CMD_SUDO + " cat /var/run/network/ifstate | grep eth0"
                else:
                    cmd = properties.CMD_SUDO + " /home/admin/bin/servicemonit " + key[0] + " status | grep running"
                result = executeCommand(cmd, [], True)
                if result[0] != 1:
                    apps1Status[key] = True
            for key in apps2Status.iterkeys():
                if  key[0] == "vsftpd" or key[0] == "tftpd-hpa":
                    cmd = properties.CMD_SUDO + " /usr/bin/service " + key[0] + " status | grep running"
                elif  key[0] == "dhcp3-server":
                    cmd = properties.CMD_SUDO + " /usr/bin/service " + key[0] + " status | grep 'is running'"
                elif  key[0] == "isc-dhcp-server":
                    cmd = properties.CMD_SUDO + " /usr/bin/service " + key[0] + " status | grep 'running'"
                else:
                    cmd = properties.CMD_SUDO + " /home/admin/bin/servicemonit " + key[0] + " status | grep running"
                result = executeCommand(cmd, [], True)
                if result[0] != 1:
                    apps2Status[key] = True
            return apps1Status, apps2Status
        except:
            logger.logMessage(logger.ERROR, 'Application Status', "Getting services status failed.")
            return apps1Status, apps2Status
    
    def restartApplication(self, service, action):
        try:
            if service == "network":
                cmd = "/usr/bin/sudo /etc/init.d/networking " + action
                result = executeCommand(cmd,[],True)
                if result[0] == 0:
                    logger.logMessage(logger.INFO,'Application Restart',"Service " + service + " restarted successfully.")
                    return True
                else:
                    logger.logMessage(logger.ERROR,'Application Restart',"Failed to restart " + service + " service.")
                    return False

            status = True
            if service == "vsftpd" or service == "tftpd-hpa" or service == "dhcp3-server" or service == "isc-dhcp-server":
                serviceCmd = "/usr/bin/sudo /usr/bin/service "
                stopStatus = 0
                startStatus = 0
            else:
                serviceCmd = "/usr/bin/sudo /home/admin/bin/servicemonit "
                stopStatus = 1
                startStatus = 0
            if action == 'restart' or action == 'stop':
                cmd = serviceCmd + service + " stop"
                result = executeCommand(cmd,[],True)
                if result[0] != stopStatus:
                    logger.logMessage(logger.ERROR,'Application Stop',"Failed to stop " + service + " service.")
                    status = False
                else:
                    logger.logMessage(logger.INFO,'Application Stop',"Service " + service + " stopped successfully.")
                    status = True

            if action == 'stop':
                return status
            time.sleep(10)

            cmd = serviceCmd + service + " start"
            result = executeCommand(cmd,[],True)
            if result[0] != startStatus:
                logger.logMessage(logger.ERROR,'Application Start',"Failed to start " + service + " service.")
                status = False
            else:
                logger.logMessage(logger.INFO,'Application Start',"Service " + service + " started successfully.")
                status = True
            return status
        except:
            logger.logMessage(logger.ERROR,'Application Restart',"Failed to restart " + service + " service.")
            return False
        
    def userMaintenanceMode(self, action, services_list):
        servicesArray = [properties.JSVC_SERVICE_NAME,'nagios','postgresql','rsyslog','nodeMgr']
        if services_list != []:
            for name in services_list:
                servicesArray.append(name)
        
        status = True
        if action == 'start':
            state = 0
        elif action == 'stop':
            state = 1

        for service in servicesArray:
            cmd = "/usr/bin/sudo /usr/bin/monit status | grep \"Process '" + service + "'\""
            monitStatus = executeCommand(cmd,[],True)[0]
            if monitStatus == 0:
                cmd = properties.CMD_SUDO + " /home/admin/bin/servicemonit " + service + " " + action
                result = executeCommand(cmd,[],True)
                if result[0] == state:
                    logger.logMessage(logger.INFO, 'MaintenanceMode', service + ": " + result[1])
                else:
                    cmd = properties.CMD_SUDO + " /home/admin/bin/servicemonit " + service + " status"
                    result = executeCommand(cmd,[],True)
                    logger.logMessage(logger.ERROR, 'MaintenanceMode', "Failed to " + action + " the service : " + result[1])
                    status = False
                time.sleep(2)
            else:
                logger.logMessage(logger.INFO,'MaintenanceMode',service + " service is not yet initialized in Monit.")
        return status
    
    def getModuleVersion(self):
        try:
            verList = {}
            fin = open(properties.FW_VERSIONS, "rb")
            lines = fin.readlines()
            fin.close()
            for line in lines:
                keyValues = line.split("=")
                keyValues[0] = keyValues[0].replace("-","")
                verList[keyValues[0]] = keyValues[1].rstrip()
            return verList
        except:
            logger.logMessage(logger.INFO, 'getModuleVersion', "Exception Caught while getting version details.")
    
    def createCoreConfig(self, macaddr):
        try:
            bdrDetails = {}
            bdrDetails['domainName'] = properties.BDRCORE_DOMAIN_NAME
            bdrDetails['maxMemory'] = "2048"
            bdrDetails['diskPath'] = properties.BDRCORE_DISK_PATH
            bdrDetails['isoPath'] = ""
            bdrDetails['bootPriority'] = "cd"
            bdrDetails['onPowerOff'] = "restart"
            bdrDetails['onReboot'] = "restart"
            bdrDetails['onCrash'] = "restart"
            netInfo = self.getNetworkInfo()
            bridge_iface = netInfo['default_iface']
            bdrDetails['bridgeInterface'] = bridge_iface
            processTemplateTOFile('config/kvmconfig', properties.BDRCORE_CONFIG_FILE, {'config':bdrDetails,'macaddr':macaddr})
            return True
        except:
            return False

    def getCoreDetails(self):
        cmd = "/usr/bin/sudo /usr/bin/virsh dumpxml " + properties.BDRCORE_DOMAIN_NAME + " | grep \"mac address\" | cut -d'=' -f2 | sed -e \"s/[',\/,\>]//g\""
        result = executeCommand(cmd, [], True)
        mac = result[1].strip().upper()
        coreDetails = {}
        coreDetails['core_macaddress'] = mac
        coreDetails['core_hostname'] = ""
        coreDetails['core_ipaddress'] = ""
        try:
            ipArr = []
            network = self.networkutils
            ipArr = network.getIPAddress().split(".")
            ipRange = ipArr[0] + "." + ipArr[1] + "." + ipArr[2] + ".0/24"
            
            cmd = "/usr/bin/sudo /usr/bin/nmap -sP " + ipRange + " | grep -i -B 2 " + mac + " | grep Nmap"
            logger.logMessage(logger.INFO, 'Core Details', 'Command - ' + cmd)
            result = executeCommand(cmd,[],True)[1]
            if result != "":
                arr = result.split(" ")
                cnt = len(arr)
                if cnt == 6:
                    coreDetails['core_hostname'] = arr[4]
                    coreDetails['core_ipaddress'] = arr[5].lstrip("(").rstrip(")")
                elif cnt == 5:
                    coreDetails['core_hostname'] = arr[4]
                    coreDetails['core_ipaddress'] = arr[4]
                return coreDetails
            else:
                ipRange = ipArr[0] + "." + ipArr[1] + ".0.0/16"
                cmd = "/usr/bin/sudo /usr/bin/nmap -sP " + ipRange + " | grep -i -B 2 " + mac + " | grep Nmap"
                logger.logMessage(logger.INFO, 'Core Details', 'Command - ' + cmd)
                result = executeCommand(cmd,[],True)[1]
                if result != "":
                    arr = result.split(" ")
                    cnt = len(arr)
                    if cnt == 6:
                        coreDetails['core_hostname'] = arr[4]
                        coreDetails['core_ipaddress'] = arr[5].lstrip("(").rstrip(")")
                    elif cnt == 5:
                        coreDetails['core_hostname'] = arr[4]
                        coreDetails['core_ipaddress'] = arr[4]
                    return coreDetails
                return coreDetails
        except:
            logger.logMessage(logger.INFO, 'Core Details', "Exception Caught while getting core details.")
            return coreDetails

    def resetProxySetting(self):
        ''' Remove Proxy Info '''
        self.cfgmanager.setProxySetting('direct')
        

    def resetToDhcp(self):
        try:
            ''' Remove Proxy Info '''
            self.resetProxySetting()
            
            ''' Reset Network Settings to DHCP '''
            networkInfo = {}
            networkInfo['hostname'] = self.getNetworkInfo()['mac'].replace(":","")
            networkInfo['domainname'] = "localdomain.com"
            networkInfo['dhcp'] = True
            self.initializeNetwork(networkInfo)
            logger.logMessage(logger.INFO, 'Reset Dhcp', "Successfully Reset to Dhcp")
            return True
        except:
            logger.logMessage(logger.ERROR, 'Reset Dhcp', "Failed to Reset to Dhcp")
            return False
    
    def resetPasswords(self):
        result = executeCommand(properties.APPLIANCE_RST_PWD_COMMAND,[],True)
        if result[0] == 0:
            logger.logMessage(logger.INFO, 'Reset Password', "Successfully Reset the password")
            return True
        else:
            logger.logMessage(logger.ERROR, 'Reset Password', "Failed to Reset the Password")
            return False

    def resetMonitoringConfigs(self):
        try:
            cmd = "/usr/bin/sudo /bin/rm -rf /nems/nagios/etc/SA/*"
            result1 = executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /bin/cp -f /nems/nagios/clientcode/templates/tm.cfg /nems/nagios/clientcode/templates/localhost.cfg /nems/nagios/etc/SA/"
            result2 = executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /bin/chown nagios:nagios /nems/nagios/etc/SA -R"
            result3 = executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /bin/rm -rf /var/lib/nagios /var/lib/monitd /nems/nagios/var/status.dat"
            result4 = executeCommand(cmd, [], True)
            if result1[0] == 0 and result2[0] == 0 and result3[0] == 0 and result4[0] == 0:
                logger.logMessage(logger.INFO, 'Remove monitoring Configs', "Successfully removed Nagios Configs.")
                return True
            else:
                logger.logMessage(logger.ERROR, 'Reset Nagios Configs', "Failed to reset Nagios Configs.")
                return False
        except:
            logger.logMessage(logger.ERROR, 'Reset Nagios Configs', "Exception Caught while resetting Nagios Configs.")
            return False

    def resetApplianceToFactoryDefaults(self):
        try:
            status, msg = self.unregisterAppliance()
            if not status:
                return False, msg
            
            if self.resetToDhcp() == False:
                return False, "Failed to change network to DHCP."

            cmd = "/usr/bin/sudo /sbin/reboot"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                return False, "Failed to reboot appliance"
            return True, 'Appliance reset to factory defaults successful'
        except Exception, msg:
            return False, "Failed to reset to factory defaults. Exception caught - " + str(msg)
        
    
    def triggerRegister(self):
        return self.regInfo.registerAppliance()
        
        
    def activateAppliance(self,server, activation_key):
        return self.regInfo.activateAppliance(server, activation_key)
    
    '''
    def resetApplinace(self):
        try:
                        
            if self.resetMonitoringConfigs() == False:
                return False, "Failed to reset Nagios configs."
            
            licenseManager = LicenseManager(self)
            if licenseManager.deleteLicense() == False:
                return False, "Failed to delete license and update monit"
            cmd = "/usr/bin/sudo /bin/sh /home/admin/bin/databasedefaults.sh"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                return False, "Failed to reset database"
            
            cmd = "/usr/bin/sudo /bin/rm -rf /var/lib/nagios"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                logger.logMessage(logger.ERROR, 'Reset Nagios Data', "Failed to delete nagios data files")
                return False, "Failed to delete nagios data files"
            else:
                logger.logMessage(logger.INFO, 'Reset Nagios Data', "Successfully deleted nagios data files")

            cmd = "/usr/bin/sudo /bin/rm -rf /etc/nsg/tmp"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                logger.logMessage(logger.ERROR, 'Tmp Files', "Failed to delete temporary files")
                return False, "Failed to delete temporary files"
            else:
                logger.logMessage(logger.INFO, 'Tmp Files', "Successfully deleted temporary files")
            return True, 'Appliance unregistered successfully to register to the new server'
        except Exception, msg:
            return False, "Failed to unregistered the appliance. Exception caught - " + str(msg)
    '''

    def checkNetwork(self):
        cmd = "/usr/bin/sudo /sbin/ethtool eth0 | /bin/grep -i 'Link detected: yes'"
        nic_status = executeCommand(cmd, [], True)[0] == 0

        if nic_status:
            netInfo = self.getNetworkInfo()
            if not netInfo['dhcp']:
                logger.logMessage(logger.INFO, 'Check Network', "Network proto is static")
                return True

            if netInfo['gateway'] != '':
                cmd = "/usr/bin/arping -c 3 -I " + netInfo['default_iface'] + " -f " + netInfo['gateway']
                result = executeCommand(cmd, [], True)
                if result[0] != 0:
                    logger.logMessage(logger.ERROR, 'Check Network Gateway', "Unable to ping gateway")
                    executeCommand(properties.CMD_NETWORK_RESTART)
                    logger.logMessage(logger.INFO, 'Check Network Gateway', "Restarted Network")
                    time.sleep(2)
                    executeCommand(properties.CMD_GEN_BANNER, [],True)
                    return True
                else:
                    logger.logMessage(logger.INFO, 'Check Network Gateway', "Gateway Ok")
            else:
                logger.logMessage(logger.ERROR, 'Check Network Gateway', "Gateway not found")
                executeCommand(properties.CMD_NETWORK_RESTART)
                logger.logMessage(logger.INFO, 'Check Network', "Restarted Network")
                time.sleep(2)
                executeCommand(properties.CMD_GEN_BANNER, [],True)
                return True
    
            if netInfo['ipaddr'] == 'UNKNOWN':
                logger.logMessage(logger.ERROR, 'Check Network IP', "IP Address not found")
                executeCommand(properties.CMD_NETWORK_RESTART)
                logger.logMessage(logger.INFO, 'Check Network IP', "Restarted Network")
                time.sleep(2)
                executeCommand(properties.CMD_GEN_BANNER, [],True)
                return True
            return True
        else:
            logger.logMessage(logger.ERROR, 'Check Network', "Network Interface Card is not UP")
            return False

    def addVlanId(self, vlan_id, iface='eth0'):
        try:
            cmd = "/usr/bin/sudo /sbin/vconfig add " + iface + " " + vlan_id
            result = executeCommand(cmd, [], True)
            errMsg = ""
            if "error:" in result[1]:
                err = result[1].split("error:")
                errMsg = err[1].strip()
            if result[0] != 0 and errMsg != "File exists":
                return False, "Unable to Configure VLAN. " + errMsg
            else:
                #cmd = "/usr/bin/sudo /sbin/ifconfig " + iface + " 0.0.0.0"
                #result = executeCommand(cmd, [], True)
                return True, 'Successfully updated network configuration.'
        except:
            return False, "Caught exception while configuring VLAN"
    
    def deleteVlanIface(self, vlan_iface=""):
        try:
            if vlan_iface == "":
                networkInfo = self.getNetworkInfo()
                vlan_iface = networkInfo['default_iface']
                vlan_id = networkInfo['vlanid']
            else:
                vlan_id = vlan_iface.split('.')[1]
            if vlan_id != "":
                cmd = "/usr/bin/sudo /sbin/vconfig rem " + vlan_iface
                result = executeCommand(cmd, [], True)
                if "error:" in result[1]:
                    err = result[1].split("error:")
                    errMsg = err[1].strip()
                if result[0] == 0:
                    self.updateVlanConfig()
                    return True, 'Successfully deleted the vlan configuration.'
                else:
                    if errMsg == "No such device":
                        return True, 'No such vlan is configured.'
                    else:
                        return False, errMsg
            else:
                return True, "No such vlan is configured."
        except Exception, emsg:
            return False, "Caught exception while deleting VLAN ID " + str(emsg)

    def deletePhyIface(self, iface=""):
        try:
            if iface == "":
                networkInfo = self.getNetworkInfo()
                iface = networkInfo['default_iface']
            
            cmd = "/usr/bin/sudo /sbin/ifconfig " + iface + " 0.0.0.0 down"
            executeCommand(cmd, [], True)
            self.updateVlanConfig()
            return True, "Successfully deleted the interface configuration."
            
        except:
            return False, "Caught exception while deleting ifterface"

    def saveVlanInfo(self, vlanInfo):
        try:
            errMsg = ""
            retMsg = ""
            cmd = "/usr/bin/sudo /sbin/vconfig add " + vlanInfo['vlanInterface'] + " " + vlanInfo['vlanID']
            result = executeCommand(cmd, [], True)
            if "error:" in result[1]:
                err = result[1].split("error:")
                errMsg = err[1].strip()
            if result[0] != 0 and errMsg != "File exists":
                retMsg = "Unable to Configure VLAN. " + errMsg
                return False, retMsg
            
            cmd = "/usr/bin/sudo /sbin/ifconfig " + vlanInfo['vlanInterface'] + "." + vlanInfo['vlanID'] + " " + vlanInfo['vlanIP'] + " netmask " + vlanInfo['vlanSubnet'] + " up"
            result = executeCommand(cmd, [], True)
            if result[0] == 0:
                self.updateVlanConfig()
                return True, 'Successfully added the VLAN configuration.'
            else:
                cmd = "/usr/bin/sudo /sbin/vconfig rem " + vlanInfo['vlanInterface'] + "." + vlanInfo['vlanID']
                result = executeCommand(cmd, [], True)
                return False, "Unable to Configure IP Address for VLAN"
        except:
            return False, "Exception caught while saving Vlan Configuration"

    def updateVlanInfo(self, vlanInfo, oldVlanInfo):
        try:
            errMsg = ""
            status, msg = self.deleteVlanIface(oldVlanInfo['vlanName'])
            if status:
                logger.logMessage(logger.INFO, 'VLAN', "Successfully deleted the old VLAN configuration")
            else:
                logger.logMessage(logger.ERROR, 'VLAN', "Failed to delete the old VLAN configuration. " + msg)
                return False, 'Failed to delete VLAN configuration. ' + msg
                
            cmd = "/usr/bin/sudo /sbin/vconfig add " + vlanInfo['vlanInterface'] + " " + vlanInfo['vlanID']
            result = executeCommand(cmd, [], True)
            if "error:" in result[1]:
                err = result[1].split("error:")
                errMsg = err[1].strip()
            if result[0] != 0 and errMsg != "File exists":
                return False, "Unable to Configure VLAN. " + errMsg
            
            cmd = "/usr/bin/sudo /sbin/ifconfig " + vlanInfo['vlanInterface'] + "." + vlanInfo['vlanID'] + " " + vlanInfo['vlanIP'] + " netmask " + vlanInfo['vlanSubnet'] + " up"
            result = executeCommand(cmd, [], True)
            if result[0] == 0:
                self.updateVlanConfig()
                return True, 'Successfully updated the VLAN configuration.'
            else:
                cmd = "/usr/bin/sudo /sbin/vconfig rem " + vlanInfo['vlanInterface'] + "." + vlanInfo['vlanID']
                result = executeCommand(cmd, [], True)
                cmd = "/usr/bin/sudo /sbin/vconfig add " + oldVlanInfo['vlanInterface'] + " " + oldVlanInfo['vlanID']
                result = executeCommand(cmd, [], True)
                cmd = "/usr/bin/sudo /sbin/ifconfig " + oldVlanInfo['vlanInterface'] + "." + oldVlanInfo['vlanID'] + " " + oldVlanInfo['vlanIP'] + " netmask " + oldVlanInfo['vlanSubnet'] + " up"
                result = executeCommand(cmd, [], True)
                self.restartApplication('network', 'restart')
                return False, "Unable to Configure IP Address for VLAN"
        except:
            return False, "Exception caught while updating Vlan Configuration"

    def updateIfaceInfo(self, info, oldInfo):
        try:    
            cmd = "/usr/bin/sudo /sbin/ifconfig " + info['iface'] + " " + info['ip'] + " netmask " + info['nm'] + " up"
            result = executeCommand(cmd, [], True)
            if result[0] == 0:
                self.updateVlanConfig()
                return True, 'Successfully updated the interface configuration.'
            else:
                return False, "Unable to Configure IP Address for interface"
        except:
            return False, "Exception caught while updating interface Configuration"

    
    def saveStaticRouteInfo(self, srouteInfo):
        try:
            if srouteInfo['srouteInterface'] == "":
                cmd = "/usr/bin/sudo /sbin/route add -net " + srouteInfo['srouteIP'] + " gw " + srouteInfo['srouteGateway'] + " netmask " + srouteInfo['srouteSubnet'] + " metric " + srouteInfo['srouteMetric']
            else:
                cmd = "/usr/bin/sudo /sbin/route add -net " + srouteInfo['srouteIP'] + " gw " + srouteInfo['srouteGateway'] + " netmask " + srouteInfo['srouteSubnet'] + " metric " + srouteInfo['srouteMetric'] + " dev " + srouteInfo['srouteInterface']
            #print cmd
            result = executeCommand(cmd, [], True)
            if result[0] == 0:
                logger.logMessage(logger.INFO,'Static Routes',"Successfully added the static route configuration")
                return True, 'Successfully added the static route configuration.'
            else:
                if result[1] == "SIOCADDRT: File exists":
                    logger.logMessage(logger.INFO,'Static Routes',"Static route configuration already exists.")
                    return True, 'Static route configuration already exists.'
                else:
                    errorMsg = result[1].split("\n")
                    logger.logMessage(logger.ERROR, 'Static Routes', "Unable to add Static Route. " + errorMsg[0])
                    return False, "Unable to add Static Route. " + errorMsg[0]
        except:
            logger.logMessage(logger.ERROR, 'Static Routes', "Exception caught while saving Static Route Configuration")
            return False, "Exception caught while saving Static Route Configuration"

    def updateStaticRouteInfo(self, srouteInfo, oldSRouteInfo):
        try:
            delStatus, delMsg = self.deleteStaticRouteInfo(oldSRouteInfo)
            if not delStatus:
                return delStatus, delMsg
            
            addStatus, addMsg = self.saveStaticRouteInfo(srouteInfo)
            if not addStatus:
                self.saveStaticRouteInfo(oldSRouteInfo)
            return addStatus, addMsg
        except:
            return False, "Exception caught while updating Static Route Configuration"

    def deleteStaticRouteInfo(self, srouteInfo):
        try:
            cmd = "/usr/bin/sudo /sbin/route del -net " + srouteInfo['srouteIP'] + " gw " + srouteInfo['srouteGateway'] + " netmask " + srouteInfo['srouteSubnet'] + " metric " + srouteInfo['srouteMetric'] + " dev " + srouteInfo['srouteInterface']
            result = executeCommand(cmd, [], True)
            if result[0] == 0:
                logger.logMessage(logger.INFO,'Static Routes',"Successfully deleted the static route configuration")
                return True, 'Successfully deleted the static route configuration.'
            else:
                if result[1] == "SIOCDELRT: No such process" or result[1] == "SIOCDELRT: No such device":
                    logger.logMessage(logger.INFO,'Static Routes',"No such static route is configured.")
                    return True, 'No such static route is configured.'
                else:
                    errorMsg = result[1].split("\n")
                    logger.logMessage(logger.ERROR, 'Static Routes', "Failed to delete Static Route configuration. " + errorMsg[0])
                    return False, 'Failed to delete Static Route configuration. ' + errorMsg[0]
        except:
            logger.logMessage(logger.ERROR, 'Static Routes', "Caught exception while deleting Static Route")
            return False, "Caught exception while deleting Static Route"

    def readFileProperties(self, filename):
        hashArr = {}
        try:
            fin = open(filename, "rb")
            lines = fin.readlines()
            fin.close()
            for line in lines:
                keyValues = line.split("=")
                hashArr[keyValues[0]] = keyValues[1].rstrip()
            return hashArr
        except:
            return hashArr
    
    def updateFileProperties(self, filename, hashArr):
        try:
            fout = open(filename, "wb")
            for key, val in hashArr.iteritems():
                fout.write(key + "=" + val + "\n")
            fout.close()
        except:
            pass
    
    def getDefBridgeNetworkInfo(self):
        try:
            bridgeInfo = {}
            bridgeInfo['bridge_ip'] = ""
            bridgeInfo['bridge_nm'] = ""
            bridgeInfo['bridge_dhcp_start'] = ""
            bridgeInfo['bridge_dhcp_end'] = ""
            bridgeInfo['is_virtualization_enabled'] = 0
            return bridgeInfo
        except:
            return bridgeInfo

    def saveDefaultBridgeNetwork(self, bridgeNwInfo):
        try:
            network = self.networkutils
            _ip_addr_arr, ip_addr_bin_arr = network.getIpBinaryArrays(bridgeNwInfo['bridge_ip'])
            _nm_arr, nm_bin_arr = network.getIpBinaryArrays(bridgeNwInfo['bridge_nm'])
            ip_start_arr, _ip_start_bin_arr = network.getIpBinaryArrays(bridgeNwInfo['bridge_dhcp_start'])
            ip_end_arr, _ip_end_binary = network.getIpBinaryArrays(bridgeNwInfo['bridge_dhcp_end'])
            
            wildcard_bin_arr = network.getOnesComplement(nm_bin_arr)

            network_bin_arr = []
            broadcast_bin_arr = []
            for x in range(0,4):
                network_bin_arr.append(str(int(ip_addr_bin_arr[x], 2) & int(nm_bin_arr[x], 2)))
                broadcast_bin_arr.append(str(int(ip_addr_bin_arr[x], 2) | int(wildcard_bin_arr[x], 2)))

            minHost = network_bin_arr
            maxHost = broadcast_bin_arr
            minHost[3] = int(minHost[3]) + 1
            maxHost[3] = int(maxHost[3]) - 1
            
            start_ip_number = network.convertIP2Number(minHost)
            end_ip_number = network.convertIP2Number(maxHost)
            dhcp_ip_start_number = network.convertIP2Number(ip_start_arr)
            dhcp_ip_end_number = network.convertIP2Number(ip_end_arr)
            
            if not ((dhcp_ip_start_number >= start_ip_number) and (dhcp_ip_start_number <= end_ip_number)):
                return "DHCP Range Start IP is not in the range of Subnet mask (" + network.joinArr2IP(minHost) + " - " + network.joinArr2IP(maxHost) + ")"
            
            if not ((dhcp_ip_end_number >= start_ip_number) and (dhcp_ip_end_number <= end_ip_number)):
                return "DHCP Range End IP is not in the range of Subnet mask (" + network.joinArr2IP(minHost) + " - " + network.joinArr2IP(maxHost) + ")"
            
            processTemplateTOFile('config/virbr0-default.xml', properties.BRIDGE_WORK_FILE ,{ 'bridgeNwInfo':bridgeNwInfo })
            cmd = "/usr/bin/sudo /usr/bin/virsh net-destroy default"
            executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /usr/bin/virsh net-undefine default"
            executeCommand(cmd, [], True) 
            cmd = "/usr/bin/sudo /usr/bin/virsh net-define " + properties.BRIDGE_WORK_FILE
            executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /usr/bin/virsh net-start default"
            executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /usr/bin/virsh net-autostart default"
            executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /bin/rm -f " + properties.BRIDGE_WORK_FILE
            executeCommand(cmd, [], True)
            cmd = "/usr/bin/sudo /bin/chmod 644 " + properties.BRIDGE_DEFAULT_FILE
            executeCommand(cmd, [], True)
            return True
        except:
            return "Exception caught while saving the VM NAT Bridge network"
    
    def checkServerConnectivity(self, host, port):
        try:
            if not host:
                return False, "", "NA"
            
            conn_type = self.cfgmanager.getProxyProperties(self.cfgmanager.NETWORK_CON_TYPE)
            if conn_type != "direct":
                proxy_ip = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_IP)
                proxy_port = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PORT)
                proxy_usr = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_USR)
                proxy_pwd = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PWD)
                
                proxy_connect = 'CONNECT %s:%s HTTP/1.1\r\n' % (host, port)
                user_agent = 'User-Agent: python\r\n'
                if proxy_usr != "" and proxy_pwd != "":
                    user_pass = base64.b64encode(proxy_usr + ':' + proxy_pwd)
                    proxy_authorization = 'Proxy-authorization: Basic ' + user_pass + '\r\n'
                    proxy_pieces = proxy_connect + proxy_authorization + user_agent + '\r\n'
                else:
                    proxy_pieces = proxy_connect + user_agent + '\r\n'
                proxy = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                proxy.settimeout(65)
                proxy.connect((proxy_ip, int(proxy_port)))
                proxy.sendall(proxy_pieces)
                response = proxy.recv(8192)
                try:
                    status = int(response.split()[1])
                except:
                    return False, response, "Unexpected HTTP Response"
                proxy.close()
                del proxy
                if status != 200:
                    logger.logMessage(logger.ERROR, 'ServerConnection', "Server connection is not ok")
                    retmsg = "Response Code : " + str(status) + ", " + self.errorcode_map.get(str(status), "Could not connect.")
                    return False, response, retmsg
                else:
                    return True, response, "Successfully Connected."
            else:
                data_recvd = ""
                conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                conn.settimeout(65)
                try:
                    conn.connect((host, int(port)))
                except socket.error as (errno, errmsg):
                    logger.logMessage(logger.ERROR, 'ServerConnection', "Exception caught: " + str(errno) + " - " + str(errmsg))
                    conn.close()
                    return False, "", errmsg

                data_recvd = conn.recv(8192)
                conn.close()
                del conn
                return True, data_recvd, "Successfully Connected."
        except Exception, errmsg:
            logger.logMessage(logger.ERROR, 'ServerConnection', "Exception caught: " + str(errmsg))
            return False, "", str(errmsg)


    def toUpdateServerURL(self, uri):
        proto = self.cfgmanager.getProperty(self.cfgmanager.CONFIG_UPDATE_SERVER_PROTOCOL)
        host = self.regInfo.server
        if proto == 'secure':
            return 'https://' + host + uri
        else:
            return 'http://' + host + uri


    def postXMLData(self, url, data):
        conn_type = self.cfgmanager.getProxyProperties(self.cfgmanager.NETWORK_CON_TYPE)
        c = pycurl.Curl()
        strio = StringIO.StringIO()

        c.setopt(pycurl.URL, str(url))
        c.setopt(pycurl.POST, 1)
        c.setopt(pycurl.VERBOSE, 0)
        if conn_type != "direct":
            proxy_ip = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_IP)
            proxy_port = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PORT)
            proxy_usr = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_USR)
            proxy_pwd = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PWD)
            c.setopt(pycurl.PROXY, proxy_ip)
            c.setopt(pycurl.PROXYPORT, int(proxy_port))
            c.setopt(pycurl.PROXYAUTH, pycurl.HTTPAUTH_BASIC)
            if proxy_usr != "" and proxy_pwd != "":
                c.setopt(pycurl.PROXYUSERPWD, proxy_usr + ":" + proxy_pwd)
            else:
                pass
        else:
            pass
        
        c.setopt(pycurl.SSL_VERIFYPEER, False)
        c.setopt(pycurl.SSL_VERIFYHOST, False)
        c.setopt(pycurl.TIMEOUT, 120)
        c.setopt(pycurl.CONNECTTIMEOUT, 60)
        c.setopt(pycurl.HTTPHEADER, ["Content-type: text/xml", "Accept: text/xml"])
        
        if data:
            c.setopt(pycurl.POSTFIELDS, str(data))

        c.setopt(pycurl.WRITEFUNCTION, strio.write)
        c.setopt(pycurl.FOLLOWLOCATION, 1)
        c.setopt(pycurl.MAXREDIRS, 5)
        c.perform()
        content = strio.getvalue()
        response = c.getinfo(pycurl.HTTP_CODE)
        return response, content


    def downloadFile(self, url, dest):
        try:
            conn_type = self.cfgmanager.getProxyProperties(self.cfgmanager.NETWORK_CON_TYPE)
            c = pycurl.Curl()
            strio = StringIO.StringIO()
    
            c.setopt(pycurl.URL, str(url))
            c.setopt(pycurl.HTTPGET, 1)
            c.setopt(pycurl.VERBOSE, 0)
            if conn_type != "direct":
                proxy_ip = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_IP)
                proxy_port = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PORT)
                proxy_usr = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_USR)
                proxy_pwd = self.cfgmanager.getProxyProperties(self.cfgmanager.PROXY_PWD)
                c.setopt(pycurl.PROXY, proxy_ip)
                c.setopt(pycurl.PROXYPORT, int(proxy_port))
                c.setopt(pycurl.PROXYAUTH, pycurl.HTTPAUTH_BASIC)
                if proxy_usr != "" and proxy_pwd != "":
                    c.setopt(pycurl.PROXYUSERPWD, proxy_usr + ":" + proxy_pwd)
                else:
                    pass
            else:
                pass
    
            c.setopt(pycurl.SSL_VERIFYPEER, False)
            c.setopt(pycurl.SSL_VERIFYHOST, False)
            c.setopt(pycurl.TIMEOUT, 120)
            c.setopt(pycurl.CONNECTTIMEOUT, 60)
    
            c.setopt(pycurl.WRITEFUNCTION, strio.write)
            c.setopt(pycurl.FOLLOWLOCATION, 1)
            c.setopt(pycurl.MAXREDIRS, 5)
    
            c.perform()
            fout = open(dest, "wb")
            fout.write(strio.getvalue())
            fout.close()
    
            cmd1 = "/usr/bin/sudo chown admin.admin " + dest + " >/dev/null 2>&1"    
            cmd2 = "/usr/bin/sudo chmod 755 " + dest + " >/dev/null 2>&1"
            executeCommand(cmd1, [], True)
            executeCommand(cmd2, [], True)
            return True
        except Exception as errmsg:
            logger.logMessage(logger.ERROR, 'downloadFile', "Failed to download file - " + str(errmsg))
            return False

    def _generateDiscoveryConfig(self, neprobe_port, msg_port):
        try:
            auth_token = self.regInfo.getRegistrationInfo()['auth_token']
            processTemplateTOFile('config/neprobe.conf', properties.DISCOVERY_CFG_WORK, { 'discovery_sender_port': neprobe_port, 'msg_sender_port': msg_port, 'nsg_mac': auth_token })
            cmd = "diff " + properties.DISCOVERY_CFG_WORK + " " + properties.DISCOVERY_CFG_DEST + " >/dev/null 2>&1"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                cmd = "/usr/bin/sudo mv -f " + properties.DISCOVERY_CFG_WORK + " " + properties.DISCOVERY_CFG_DEST + " >/dev/null 2>&1"
                result = executeCommand(cmd)
                cmd1 = "/usr/bin/sudo chown nems.nems " + properties.DISCOVERY_CFG_DEST + " >/dev/null 2>&1"    
                cmd2 = "/usr/bin/sudo chmod 755 " + properties.DISCOVERY_CFG_DEST + " >/dev/null 2>&1"
                executeCommand(cmd1, [], True)
                executeCommand(cmd2, [], True)
                if result[0] != 0:
                    return 2
                else:
                    return 1
#                    try:
#                        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#                        #sock.setblocking(0)  # optional non-blocking
#                        sock.connect(('127.0.0.1', 9876))
#                        string = 'sarath'
#                        sock.send(string)
#                        sock.close()
#                    except:
#                        pass
            else:
                #there is no difference
                os.remove(properties.DISCOVERY_CFG_WORK)
            return 0
        except:
            return 2

    '''
    def _generateNEMONConfig(self, port):
        try:
            auth_token = self.regInfo.getRegistrationInfo()['auth_token']
            processTemplateTOFile('config/clientcode.cfg', properties.NEMON_CFG_WORK, { 'nemon_sender_port':port, 'registration_id':auth_token })
            # check for difference 
            cmd = "diff " + properties.NEMON_CFG_WORK + " " + properties.NEMON_CFG_DEST + " >/dev/null 2>&1"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                cmd = "/usr/bin/sudo mv -f " + properties.NEMON_CFG_WORK + " " + properties.NEMON_CFG_DEST + " >/dev/null 2>&1"
                result = executeCommand(cmd)
                cmd1 = "/usr/bin/sudo chown nagios.nagios " + properties.NEMON_CFG_DEST + " >/dev/null 2>&1"    
                cmd2 = "/usr/bin/sudo chmod 755 " + properties.NEMON_CFG_DEST + " >/dev/null 2>&1"
                executeCommand(cmd1, [], True)
                executeCommand(cmd2, [], True)
                if result[0] != 0:
                    return 2
                else:
                    return 1
            else:
                #if there is no difference
                os.remove(properties.NEMON_CFG_WORK)
            return 0
        except:
            return 2
    '''

    def _generateNodeManagerConfig(self, port):
        try:
            processTemplateTOFile('config/nodeMgr', properties.NODEMGR_CFG_WORK, { 'tunnel_port': port })
            # check for difference
            cmd = "diff " + properties.NODEMGR_CFG_WORK + " " + properties.NODEMGR_CFG_DEST + " >/dev/null 2>&1"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                cmd = "/usr/bin/sudo mv -f " + properties.NODEMGR_CFG_WORK + " " + properties.NODEMGR_CFG_DEST + " >/dev/null 2>&1"
                result = executeCommand(cmd)
                cmd1 = "/usr/bin/sudo chown admin.admin " + properties.NODEMGR_CFG_DEST + " >/dev/null 2>&1"    
                cmd2 = "/usr/bin/sudo chmod 755 " + properties.NODEMGR_CFG_DEST + " >/dev/null 2>&1"
                executeCommand(cmd1, [], True)
                executeCommand(cmd2, [], True)
                if result[0] != 0:
                    return 2
                else:
                    return 1
            else:
                #there is no difference
                os.remove(properties.NODEMGR_CFG_WORK)
            return 0
        except:
            return 2 

    def _generateGoogleBufferConfig(self, port):
        try:
            processTemplateTOFile('config/monitoring.properties', properties.MON_CFG_WORK, { 'google_buffer_port': port })
            # check for difference 
            cmd = "diff " + properties.MON_CFG_WORK + " " + properties.MON_CFG_DEST + " >/dev/null 2>&1"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                cmd = "/usr/bin/sudo mv -f " + properties.MON_CFG_WORK + " " + properties.MON_CFG_DEST + " >/dev/null 2>&1"
                result = executeCommand(cmd)
                cmd = "/usr/bin/sudo chmod 755 " + properties.MON_CFG_DEST + " >/dev/null 2>&1"
                executeCommand(cmd, [], True)
                if result[0] != 0:
                    return 2
                else:
                    return 1
            else:
                #if there is no difference
                os.remove(properties.MON_CFG_WORK)
            return 0
        except:
            return 2

    def generateConfig(self, service, port):
        if service == 'NODEMGR':
            returnval = self._generateNodeManagerConfig(port)
            if returnval == 2:
                return False
            elif returnval == 1:
                cmd = "/usr/bin/sudo /home/admin/bin/servicemonit nodeMgr restart>/dev/null 2>&1"
                result = executeCommand(cmd, [], True)
                if result[0] != 0:
                    logger.logMessage(logger.ERROR, 'GenerateConfig', "Failed to start NODE MANAGER service after configuration update.")
                    return False
            return True
        
        
#        elif service == 'NEMON':
#            returnval = self._generateNEMONConfig(port)
#            if returnval == 2:
#                return False
#            return True
        elif service == 'DISCO' or service == 'NEPROBE':
            returnval = self._generateDiscoveryConfig(port['NEPROBE'], port['MSG'])
            if returnval == 2:
                return False
            return True
        elif service == 'NDA' or service == 'NSGMON':
            returnval = self._generateGoogleBufferConfig(port)
            if returnval == 2:
                return False
            return True
        else:
            logger.logMessage(logger.WARN, 'GenerateConfig', "Unsupported service " + service)
            return True
        return False

    '''
    def updateMonit(self, serviceArr=[]):
        try:
            filename = ""
            reloadFlag = False
            for service in serviceArr:
                updateFlag = False
                if service == "monitoring":
                    filename = "monitoring.monitrc"
                    updateFlag = True
                if service == "neprobe" or service == "discovery":
                    filename = "neprobe.monitrc"
                    nsg_mac = self.appliance.macaddress
                    cmd = """sudo sed -i -e 's/^gateway.uuid=.*$/gateway.uuid=%s/g' %s""" % (nsg_mac, properties.DISCOVERY_CFG_DEST)
                    executeCommand(cmd, [], True)
                    updateFlag = True

                if updateFlag:
                    processTemplateTOFile('config/' + filename, properties.WORK_DIR + filename, {})
                    cmd = "diff " + properties.WORK_DIR + filename + " " + properties.MONITRC_CFG_DIR + filename + " >/dev/null 2>&1"
                    result = executeCommand(cmd, [], True)
                    if result[0] != 0:
                        cmd = "/usr/bin/sudo /bin/mv -f " + properties.WORK_DIR + filename + " " + properties.MONITRC_CFG_DIR + filename + " >/dev/null 2>&1"
                        result = executeCommand(cmd)
                        cmd1 = "/usr/bin/sudo chown root.root " + properties.MONITRC_CFG_DIR + filename + " >/dev/null 2>&1"    
                        cmd2 = "/usr/bin/sudo chmod 700 " + properties.MONITRC_CFG_DIR + filename + " >/dev/null 2>&1"
                        executeCommand(cmd1, [], True)
                        executeCommand(cmd2, [], True)
                        if result[0] != 0:
                            logger.logMessage(logger.INFO,'updateMonit','Failed to update MONIT configuration file for ' + service + ' service.')
                            return False
                        else:
                            reloadFlag = True
                            logger.logMessage(logger.INFO,'updateMonit','MONIT configuration file for ' + service + ' service is updated.')
                    else:
                        #there is no difference
                        logger.logMessage(logger.INFO,'updateMonit',"MONIT configuration file for " + service + " service is already updated.")
                        os.remove(properties.WORK_DIR + filename)

            if reloadFlag or not serviceArr:
                cmd = "/usr/bin/sudo /usr/bin/monit reload"
                result = executeCommand(cmd, [], True)
                if result[0] != 0:
                    logger.logMessage(logger.ERROR,'updateMonit',"Failed to reload MONIT service after configuration update.")
                    return False
                else:
                    logger.logMessage(logger.INFO,'updateMonit',result[1])
            return True
        except:
            logger.logMessage(logger.ERROR,'updateMonit',"Failed to update monit exception caught")
            return False
    '''
    
    def unregisterAppliance(self):
        try:
            msg = ""
            if not self.kill_tunnels():
                msg += "Failed to disconnect the tunnel "
            
            self.regInfo.deRegistered()
            
            if not self.resetPasswords():
                msg += "Failed to reset user's credential "
                
            if self.resetMonitoringConfigs() == False:
                msg += "Failed to remove monitoring configs "
            
            cmd = "/usr/bin/sudo /bin/sh /home/admin/bin/databasedefaults.sh"
            result = executeCommand(cmd, [], True)
            if result[0] != 0:
                msg += "Failed to reset database "
                
            cmd = "/bin/grep \'<cmgrlogs_dir>\' " + properties.NEMON_CFG_DEST
            try:
                result = executeCommand(cmd, [], True)[1].split('=')[1].strip()
                cmd = "/usr/bin/sudo  /bin/rm -f " + result + "/cmr* " + result + "/cdr*"
                executeCommand(cmd, [], True)
            except:
                pass
            
            self.removeServices()
            
            if msg:
                return False, msg
            return True, "Successfully de-register the Appliance."
        except:
            pass
                

    def removeServices(self):
        cmd = "/usr/bin/sudo /bin/rm -rf " + properties.MONITRC_CFG_DIR + 'monitoring.monitrc'
        executeCommand(cmd, [], True)
        cmd = "/usr/bin/sudo /bin/rm -rf " + properties.MONITRC_CFG_DIR + 'neprobe.monitrc'
        executeCommand(cmd, [], True)
        #cmd = "/usr/bin/sudo /bin/rm -rf " + properties.MONITRC_CFG_DIR + 'alertd.monitrc'
        #executeCommand(cmd, [], True)
        #cmd = "/usr/bin/sudo /bin/rm -rf " + properties.MONITRC_CFG_DIR + 'mongodb.monitrc'
        #executeCommand(cmd, [], True)
        cmd = "/usr/bin/sudo /bin/rm -rf " + properties.MONITRC_CFG_DIR + 'nodeMgr.monitrc'
        executeCommand(cmd, [], True)
        cmd = "/usr/bin/sudo /bin/rm -rf " + properties.MONITRC_CFG_DIR + 'postgresql.monitrc'
        executeCommand(cmd, [], True)

        cmd = "/usr/bin/sudo /home/admin/bin/servicemonit nagios stop"
        executeCommand(cmd, [], True)
        cmd = "/usr/bin/sudo /home/admin/bin/servicemonit neprobe stop"
        executeCommand(cmd, [], True)
        #cmd = "/usr/bin/sudo /home/admin/bin/servicemonit alertd stop"
        #executeCommand(cmd, [], True)
        #cmd = "/usr/bin/sudo /home/admin/bin/servicemonit mongodb stop"
        #executeCommand(cmd, [], True)
        cmd = "/usr/bin/sudo /home/admin/bin/servicemonit nodeMgr stop"
        executeCommand(cmd, [], True)
        cmd = "/usr/bin/sudo /home/admin/bin/servicemonit postgresql stop"
        executeCommand(cmd, [], True)
        cmd = "/usr/bin/sudo /usr/sbin/service monit restart"
        executeCommand(cmd, [], True)
    
    # Kill present tunnels 
    def kill_tunnels(self):
        return self.tunnelInfo.kill_tunnels()
        
    def getRegistrationInfo(self):
        return self.regInfo.getRegistrationInfo()
    
    def getTunnelInfo(self):
        return self.tunnelInfo.getTunnelInfo()
    
    def getDebugInfo(self):
        return self.debugInfo.getDebugInfo()
    
    def prepareDebugInfo(self):
        return self.debugInfo.prepareDebugInfo()


